Page({
  data: {
  
    termList: [],
    termIndex: 0,
    classList: [{ id: 0, name: '全部班级' }],
    classIndex: 0,
    courseList: [{ id: 0, name: '全部课程' }],
    courseIndex: 0,
    statusList: ['全部', '及格', '不及格'],
    statusIndex: 0,
    statistics: {
      total: 0,
      avgScore: 0,
      passRate: 0,
      excellentRate: 0
    },
    gradesList: [],
    showGradeModal: false,
    isEdit: false,
    currentGrade: {},
    formClassIndex: 0,
    studentList: [{ id: 0, name: '请选择学生' }],
    studentIndex: 0,
    formCourseList: [{ id: 0, name: '请选择课程' }],
    formCourseIndex: 0,
    formGrade: {
      regular: '',
      midterm: '',
      final: '',
      total: '',
      level: '',
      notes: ''
    }
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad(options) {
    // 获取班级列表
    this.fetchClassList();
    
    // 获取课程列表
    this.fetchCourseList();
    
    // 获取学期列表
    this.fetchTermList();
    
    // 删除不存在的函数调用
    // this.fetchGradesList();
    
    // 获取成绩数据
    this.fetchGradesData();
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady() {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow() {
    // 页面显示时刷新数据
    this.fetchGradesData();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh() {
    // 下拉刷新
    this.fetchGradesData();
    wx.stopPullDownRefresh();
  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom() {
    // 可以在这里实现加载更多数据
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage() {

  },

  // 获取班级列表
  fetchClassList: function() {
    wx.request({
      url: 'http://localhost:3000/api/admin/classes',
      method: 'GET',
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      success: (res) => {
        if (res.statusCode === 200) {
          const classes = [{ id: 0, name: '全部班级' }, ...res.data];
          this.setData({
            classList: classes
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '获取班级列表失败',
          icon: 'none'
        });
      }
    });
  },

  // 获取课程列表
  fetchCourseList: function() {
    wx.request({
      url: 'http://localhost:3000/api/admin/courses',
      method: 'GET',
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      success: (res) => {
        if (res.statusCode === 200) {
          const courses = [{ id: 0, name: '全部课程' }, ...res.data];
          this.setData({
            courseList: courses,
            formCourseList: res.data
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '获取课程列表失败',
          icon: 'none'
        });
      }
    });
  },

  // 获取学期列表
  fetchTermList: function() {
    const app = getApp();
    const serverUrl = app.globalData.serverUrl || 'http://localhost:3000';
    
    wx.showLoading({
      title: '加载学期数据...',
    });
    
    wx.request({
      // 使用与课表页面相同的API端点
      url: `${serverUrl}/api/admin/timetable/semesters`,
      method: 'GET',
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      success: (res) => {
        wx.hideLoading();
        console.log('获取学期列表成功:', res.data);
        
        if (res.statusCode === 200) {
          const semestersData = res.data || [];
          
          if (semestersData.length > 0) {
            // 直接使用返回的学期数据，提取name属性作为显示名称
            const termList = semestersData.map(semester => semester.name || semester.id);
            
            console.log('处理后的学期列表:', termList);
            
            this.setData({
              termList: termList,
              termIndex: 0
            }, () => {
              // 在回调中确保termList已经设置完成后再获取成绩数据
              console.log('设置学期列表完成，当前学期列表:', this.data.termList);
              this.fetchGradesData();
            });
          } else {
            // 设置默认值
            this.setData({
              termList: ['2023-2024学年第一学期', '2023-2024学年第二学期', '2022-2023学年第一学期', '2022-2023学年第二学期']
            }, () => {
              this.fetchGradesData();
            });
          }
        } else {
          console.error('获取学期列表失败:', res);
          // 设置默认值
          this.setData({
            termList: ['2023-2024学年第一学期', '2023-2024学年第二学期', '2022-2023学年第一学期', '2022-2023学年第二学期']
          });
          this.fetchGradesData();
        }
      },
      fail: (err) => {
        wx.hideLoading();
        console.error('获取学期列表请求失败:', err);
        // 如果请求失败，设置默认值
        this.setData({
          termList: ['2023-2024学年第一学期', '2023-2024学年第二学期', '2022-2023学年第一学期', '2022-2023学年第二学期']
        });
        // 使用默认学期获取成绩数据
        this.fetchGradesData();
      }
    });
  },

  // 获取成绩数据
  fetchGradesData: function() {
    // 检查termList是否有数据
    if (!this.data.termList || this.data.termList.length === 0) {
      console.log('学期列表为空，无法获取成绩数据');
      return;
    }
    
    console.log('开始获取成绩数据，当前学期:', this.data.termList[this.data.termIndex]);
    
    wx.showLoading({
      title: '加载中...',
    });
    
    const classId = this.data.classList[this.data.classIndex].id;
    const courseId = this.data.courseList[this.data.courseIndex].id;
    const status = this.data.statusList[this.data.statusIndex];
    const term = this.data.termList[this.data.termIndex];
    
    wx.request({
      url: 'http://localhost:3000/api/admin/grades',
      method: 'GET',
      data: {
        classId: classId === 0 ? '' : classId,
        courseId: courseId === 0 ? '' : courseId,
        status: status === '全部' ? '' : status,
        term: term
      },
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      success: (res) => {
        wx.hideLoading();
        
        if (res.statusCode === 200) {
          console.log('获取成绩数据成功:', res.data);
          
          // 处理成绩数据，适配前端显示格式
          const processedGrades = res.data.records.map(grade => {
            return {
              ...grade,
              // 如果后端只返回总分，则将总分赋值给total
              total: grade.total || grade.score || 0,
              // 如果没有细分成绩，可以根据总分估算
              regular: grade.regular || Math.round(grade.score * 0.3) || 0,
              midterm: grade.midterm || Math.round(grade.score * 0.2) || 0,
              final: grade.final || Math.round(grade.score * 0.5) || 0,
              // 确保有等级信息
              level: grade.level || this.calculateLevel(grade.score || 0)
            };
          });
          
          // 处理统计数据
          const processedStats = {
            ...res.data.statistics,
            // 如果平均分为null，计算平均分
            avgScore: res.data.statistics.avgScore !== null ? 
                      res.data.statistics.avgScore : 
                      this.calculateAvgScore(processedGrades)
          };
          
          this.setData({
            gradesList: processedGrades,
            statistics: processedStats
          });
        }
      },
      fail: () => {
        wx.hideLoading();
        wx.showToast({
          title: '获取成绩数据失败',
          icon: 'none'
        });
      }
    });
  },

  // 根据分数计算等级
  calculateLevel: function(score) {
    score = parseFloat(score);
    if (score >= 90) {
      return 'A';
    } else if (score >= 85) {
      return 'A-';
    } else if (score >= 80) {
      return 'B+';
    } else if (score >= 75) {
      return 'B';
    } else if (score >= 70) {
      return 'B-';
    } else if (score >= 65) {
      return 'C+';
    } else if (score >= 60) {
      return 'C';
    } else if (score >= 55) {
      return 'D';
    } else {
      return 'F';
    }
  },
  
  // 计算平均分
  calculateAvgScore: function(grades) {
    if (!grades || grades.length === 0) {
      return 0;
    }
    
    const totalScore = grades.reduce((sum, grade) => {
      const score = parseFloat(grade.score || grade.total || 0);
      return sum + score;
    }, 0);
    
    return (totalScore / grades.length).toFixed(1);
  },

  // 学期变更
  termChange: function(e) {
    this.setData({
      termIndex: e.detail.value
    });
    
    this.fetchGradesData();
  },

  // 班级变更
  classChange: function(e) {
    this.setData({
      classIndex: e.detail.value
    });
  },

  // 课程变更
  courseChange: function(e) {
    this.setData({
      courseIndex: e.detail.value
    });
  },

  // 状态变更
  statusChange: function(e) {
    this.setData({
      statusIndex: e.detail.value
    });
  },

  // 筛选成绩
  filterGrades: function() {
    this.fetchGradesData();
  },

  // 重置筛选
  resetFilter: function() {
    this.setData({
      classIndex: 0,
      courseIndex: 0,
      statusIndex: 0
    });
    
    this.fetchGradesData();
  },

  // 获取等级样式类
  getLevelClass: function(level) {
    switch(level) {
      case 'A+':
      case 'A':
      case 'A-':
        return 'excellent';
      case 'B+':
      case 'B':
      case 'B-':
        return 'good';
      case 'C+':
      case 'C':
      case 'C-':
        return 'average';
      case 'D':
        return 'pass';
      case 'F':
        return 'fail';
      default:
        return '';
    }
  },

  // 添加成绩
  addGrade: function() {
    this.setData({
      showGradeModal: true,
      isEdit: false,
      formClassIndex: 0,
      studentIndex: 0,
      formCourseIndex: 0,
      formGrade: {
        regular: '',
        midterm: '',
        final: '',
        total: '',
        level: '',
        notes: ''
      }
    });
    
    // 获取学生列表
    this.fetchStudentList(this.data.classList[1].id);
  },

  // 修改成绩
  editGrade: function(e) {
    const id = e.currentTarget.dataset.id;
    const grade = this.data.gradesList.find(item => item.id === id);
    
    if (grade) {
      // 查找对应的班级索引
      let classIndex = 0;
      this.data.classList.forEach((cls, index) => {
        if (cls.name.includes(grade.className)) {
          classIndex = index - 1; // 减1是因为formClassIndex不包含"全部班级"
        }
      });
      
      this.setData({
        showGradeModal: true,
        isEdit: true,
        currentGrade: grade,
        formClassIndex: Math.max(0, classIndex),
        formGrade: {
          regular: grade.regular,
          midterm: grade.midterm,
          final: grade.final,
          total: grade.total,
          level: grade.level,
          notes: grade.notes || ''
        }
      });
      
      // 如果有班级信息，获取该班级的学生列表
      if (grade.classId) {
        this.fetchStudentList(grade.classId);
        
        // 设置学生索引
        setTimeout(() => {
          let studentIndex = 0;
          this.data.studentList.forEach((student, index) => {
            if (student.id === grade.studentId || student.studentId === grade.studentId) {
              studentIndex = index;
            }
          });
          
          this.setData({
            studentIndex: studentIndex
          });
        }, 500);
      }
    }
  },

  // 获取学生列表
  fetchStudentList: function(classId) {
    wx.request({
      url: `http://localhost:3000/api/admin/classes/${classId}/students`,
      method: 'GET',
      header: {
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      success: (res) => {
        if (res.statusCode === 200) {
          this.setData({
            studentList: res.data
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '获取学生列表失败',
          icon: 'none'
        });
      }
    });
  },

  // 表单班级变更
  formClassChange: function(e) {
    const index = e.detail.value;
    this.setData({
      formClassIndex: index
    });
    
    // 获取该班级的学生列表
    const classId = this.data.classList[parseInt(index) + 1].id;
    this.fetchStudentList(classId);
  },

  // 学生变更
  studentChange: function(e) {
    this.setData({
      studentIndex: e.detail.value
    });
  },

  // 表单课程变更
  formCourseChange: function(e) {
    this.setData({
      formCourseIndex: e.detail.value
    });
  },

  // 平时成绩输入
  regularInput: function(e) {
    this.setData({
      'formGrade.regular': e.detail.value
    });
    // 自动计算总评
    if (this.data.formGrade.midterm && this.data.formGrade.final) {
      this.calculateTotal();
    }
  },

  // 期中成绩输入
  midtermInput: function(e) {
    this.setData({
      'formGrade.midterm': e.detail.value
    });
    // 自动计算总评
    if (this.data.formGrade.regular && this.data.formGrade.final) {
      this.calculateTotal();
    }
  },

  // 期末成绩输入
  finalInput: function(e) {
    this.setData({
      'formGrade.final': e.detail.value
    });
    // 自动计算总评
    if (this.data.formGrade.regular && this.data.formGrade.midterm) {
      this.calculateTotal();
    }
  },

  // 备注输入
  notesInput: function(e) {
    this.setData({
      'formGrade.notes': e.detail.value
    });
  },

  // 计算总评
  calculateTotal: function() {
    const regular = parseFloat(this.data.formGrade.regular) || 0;
    const midterm = parseFloat(this.data.formGrade.midterm) || 0;
    const final = parseFloat(this.data.formGrade.final) || 0;
    
    // 计算总评成绩 (平时30%，期中20%，期末50%)
    const total = (regular * 0.3 + midterm * 0.2 + final * 0.5).toFixed(1);
    
    // 计算等级
    let level = '';
    if (total >= 90) {
      level = 'A';
    } else if (total >= 85) {
      level = 'A-';
    } else if (total >= 80) {
      level = 'B+';
    } else if (total >= 75) {
      level = 'B';
    } else if (total >= 70) {
      level = 'B-';
    } else if (total >= 65) {
      level = 'C+';
    } else if (total >= 60) {
      level = 'C';
    } else if (total >= 55) {
      level = 'D';
    } else {
      level = 'F';
    }
    
    this.setData({
      'formGrade.total': total,
      'formGrade.level': level
    });
  },

  // 保存成绩
  saveGrade: function() {
    // 表单验证
    if (!this.data.isEdit) {
      if (this.data.formClassIndex === 0) {
        wx.showToast({
          title: '请选择班级',
          icon: 'none'
        });
        return;
      }
      
      if (this.data.studentIndex === 0) {
        wx.showToast({
          title: '请选择学生',
          icon: 'none'
        });
        return;
      }
      
      if (this.data.formCourseIndex === 0) {
        wx.showToast({
          title: '请选择课程',
          icon: 'none'
        });
        return;
      }
    }
    
    // 验证成绩输入
    const regular = parseFloat(this.data.formGrade.regular);
    const midterm = parseFloat(this.data.formGrade.midterm);
    const final = parseFloat(this.data.formGrade.final);
    
    if (isNaN(regular) || regular < 0 || regular > 100) {
      wx.showToast({
        title: '平时成绩应在0-100之间',
        icon: 'none'
      });
      return;
    }
    
    if (isNaN(midterm) || midterm < 0 || midterm > 100) {
      wx.showToast({
        title: '期中成绩应在0-100之间',
        icon: 'none'
      });
      return;
    }
    
    if (isNaN(final) || final < 0 || final > 100) {
      wx.showToast({
        title: '期末成绩应在0-100之间',
        icon: 'none'
      });
      return;
    }
    
    // 如果总评为空，先计算总评
    if (!this.data.formGrade.total) {
      this.calculateTotal();
    }
    
    wx.showLoading({
      title: '保存中...',
    });
    
    if (!this.data.isEdit) {
      // 新增成绩
      const requestData = {
        studentId: this.data.studentList[this.data.studentIndex].id,
        courseId: this.data.formCourseList[this.data.formCourseIndex].id,
        term: this.data.termList[this.data.termIndex],
        score: parseFloat(this.data.formGrade.total)
      };
      
      // 只有当notes不为空时才添加到请求数据中
      if (this.data.formGrade.notes) {
        requestData.notes = this.data.formGrade.notes;
      }
      
      wx.request({
        url: 'http://localhost:3000/api/admin/grades',
        method: 'POST',
        data: requestData,
        header: {
          'Authorization': 'Bearer ' + wx.getStorageSync('token'),
          'Content-Type': 'application/json'
        },
        success: (res) => {
          wx.hideLoading();
          
          if (res.statusCode === 200 || res.statusCode === 201) {
            wx.showToast({
              title: '保存成功',
              icon: 'success'
            });
            
            // 关闭弹窗并刷新数据
            this.setData({
              showGradeModal: false
            });
            
            this.fetchGradesData();
          } else {
            wx.showToast({
              title: res.data.message || '保存失败',
              icon: 'none'
            });
          }
        },
        fail: () => {
          wx.hideLoading();
          wx.showToast({
            title: '保存失败，请检查网络',
            icon: 'none'
          });
        }
      });
    } else {
      // 修改成绩 - 只发送score字段
      const requestData = {
        score: parseFloat(this.data.formGrade.total)
      };
      
      // 只有当notes不为空时才添加到请求数据中
      if (this.data.formGrade.notes) {
        requestData.notes = this.data.formGrade.notes;
      }
      
      console.log('修改成绩请求数据(简化版):', requestData);
      
      wx.request({
        url: 'http://localhost:3000/api/admin/grades/' + this.data.currentGrade.id,
        method: 'PUT',
        data: requestData,
        header: {
          'Authorization': 'Bearer ' + wx.getStorageSync('token'),
          'Content-Type': 'application/json'
        },
        success: (res) => {
          wx.hideLoading();
          console.log('修改成绩响应:', res);
          
          if (res.statusCode === 200) {
            wx.showToast({
              title: '保存成功',
              icon: 'success'
            });
            
            // 关闭弹窗并刷新数据
            this.setData({
              showGradeModal: false
            });
            
            this.fetchGradesData();
          } else {
            wx.showToast({
              title: res.data.message || '保存失败',
              icon: 'none'
            });
          }
        },
        fail: (err) => {
          wx.hideLoading();
          console.error('修改成绩请求失败:', err);
          wx.showToast({
            title: '保存失败，请检查网络',
            icon: 'none'
          });
        }
      });
    }
  },

  // 关闭弹窗
  closeModal: function() {
    this.setData({
      showGradeModal: false
    });
  },

  // 导入成绩
  importGrades: function() {
    wx.showModal({
      title: '批量导入成绩',
      content: '请下载成绩导入模板，填写后上传到系统后台',
      confirmText: '下载模板',
      success: (res) => {
        if (res.confirm) {
          wx.showLoading({
            title: '准备下载...',
          });
          
          const app = getApp();
          const serverUrl = app.globalData.serverUrl || 'http://localhost:3000';
          
          // 使用正式路由
          wx.downloadFile({
            url: `${serverUrl}/api/admin/grades/template-direct`, // 暂时继续使用测试路由，确保功能正常
            header: {
              'Authorization': 'Bearer ' + wx.getStorageSync('token')
            },
            success: (res) => {
              wx.hideLoading();
              
              if (res.statusCode === 200) {
                // 保存文件到本地
                const tempFilePath = res.tempFilePath;
                
                // 打开文件
                wx.openDocument({
                  filePath: tempFilePath,
                  showMenu: true,
                  success: function() {
                    console.log('打开文档成功');
                  },
                  fail: function(error) {
                    console.error('打开文档失败', error);
                    wx.showToast({
                      title: '无法打开文件，请手动下载',
                      icon: 'none'
                    });
                  }
                });
              } else {
                wx.showToast({
                  title: '下载模板失败',
                  icon: 'none'
                });
              }
            },
            fail: (error) => {
              wx.hideLoading();
              console.error('下载模板失败:', error);
              wx.showToast({
                title: '下载模板失败，请检查网络',
                icon: 'none'
              });
            }
          });
        }
      }
    });
  },

  // 导出成绩
  exportGrades: function() {
    const that = this;
    // Fix: Get filter values directly from the data properties instead of this.data.filter
    const classId = this.data.classList[this.data.classIndex].id;
    const courseId = this.data.courseList[this.data.courseIndex].id;
    const status = this.data.statusList[this.data.statusIndex];
    const term = this.data.termList[this.data.termIndex];
    
    wx.showLoading({
      title: '正在导出...',
    });
    
    const app = getApp();
    const serverUrl = app.globalData.serverUrl || 'http://localhost:3000';
    
    // 发送请求到服务器导出成绩
    wx.request({
      url: `${serverUrl}/api/admin/grades/export`,
      method: 'POST',
      header: {
        'Content-Type': 'application/json',
        'Authorization': 'Bearer ' + wx.getStorageSync('token')
      },
      data: {
        classId: classId === 0 ? '' : classId,
        courseId: courseId === 0 ? '' : courseId,
        status: status === '全部' ? '' : status,
        term: term
      },
      responseType: 'arraybuffer', // 重要：指定响应类型为二进制数据
      success: function(res) {
        wx.hideLoading();
        
        if (res.statusCode === 200) {
          // 将二进制数据保存为临时文件
          const fs = wx.getFileSystemManager();
          const tempFilePath = `${wx.env.USER_DATA_PATH}/grades_export_${new Date().getTime()}.xlsx`;
          
          fs.writeFile({
            filePath: tempFilePath,
            data: res.data,
            encoding: 'binary',
            success: function() {
              // 直接打开文件
              wx.openDocument({
                filePath: tempFilePath,
                showMenu: true,
                success: function() {
                  console.log('成绩导出文件打开成功');
                },
                fail: function(error) {
                  console.error('打开文件失败', error);
                  wx.showModal({
                    title: '提示',
                    content: '文件已导出，但无法直接打开，请到系统后台下载',
                    showCancel: false
                  });
                }
              });
            },
            fail: function(error) {
              console.error('保存文件失败', error);
              wx.showModal({
                title: '导出失败',
                content: '无法保存导出文件',
                showCancel: false
              });
            }
          });
        } else if (res.statusCode === 404) {
          wx.showModal({
            title: '导出失败',
            content: '未找到符合条件的成绩记录',
            showCancel: false
          });
        } else {
          wx.showModal({
            title: '导出失败',
            content: '服务器错误，请稍后重试',
            showCancel: false
          });
        }
      },
      fail: function(error) {
        wx.hideLoading();
        console.error('导出成绩请求失败', error);
        wx.showModal({
          title: '导出失败',
          content: '网络错误，请检查网络连接',
          showCancel: false
        });
      }
    });
  },

  // 查看成绩分析
  viewAnalysis: function() {
    // 传递当前筛选条件到分析页面
    const classId = this.data.classList[this.data.classIndex].id;
    const courseId = this.data.courseList[this.data.courseIndex].id;
    const term = this.data.termList[this.data.termIndex];
    
    wx.navigateTo({
      url: '/pages/admin/grades/analysis/analysis?classId=' + classId + '&courseId=' + courseId + '&term=' + encodeURIComponent(term),
      success: function() {
        console.log('成功跳转到成绩分析页面');
      },
      fail: function(error) {
        console.error('跳转到成绩分析页面失败:', error);
        // 如果跳转失败，尝试跳转到教师端分析页面
        wx.showModal({
          title: '提示',
          content: '管理员成绩分析页面无法访问，是否查看教师端分析页面？',
          success: (res) => {
            if (res.confirm) {
              wx.navigateTo({
                url: '/pages/teacher/analysis/analysis'
              });
            }
          }
        });
      }
    });
  }
})